package net.sf.rose.jdbc;

import java.sql.Timestamp;
import java.text.ParseException;
import java.util.Date;

import net.sf.rose.exception.SystemErrorCode;
import net.sf.rose.exception.SystemException;

import org.apache.commons.lang.time.DateUtils;
import org.apache.log4j.Logger;

public class DataParser {

	private static Logger logger = Logger.getLogger(DataParser.class);

	/**
	 * 功能:将数据转换成指定格式
	 * 
	 * @param type
	 * @param value
	 */
	public Object parse(String type, Object value, String format) {
		if ("java.lang.String".equals(type)) {
		} else if ("java.lang.Integer".equals(type)) {
			value = Integer.parseInt(value.toString());
		} else if ("java.math.BigDecimal".equals(type)) {
			value = new java.math.BigDecimal(value.toString());
		} else if ("java.sql.Timestamp".equals(type)) {
			if (!(value instanceof java.sql.Timestamp)) {
				value = new Timestamp((toDate(value.toString())).getTime());
			}
		} else if ("java.lang.Long".equals(type)) {
			value = Long.parseLong(value.toString());
		} else if ("java.lang.Double".equals(type)) {
			value = Double.parseDouble(value.toString());
		} else if ("java.lang.Float".equals(type)) {
			value = Float.parseFloat(value.toString());
		} else if ("java.lang.Byte".equals(type)) {
			value = Byte.parseByte(value.toString());
		} else if ("java.util.Date".equals(type)) {
			value = new Timestamp((toDate(value.toString())).getTime());
		}
		return value;
	}

	private static String[] dataPatterns = null;

	static {
		dataPatterns = new String[3];
		dataPatterns[0] = "yyyy-MM-dd HH:mm:ss";
		dataPatterns[1] = "yyyy-MM-dd";
		dataPatterns[2] = "yyyy-MM-dd HH:mm:ss a";
	}

	/**
	 * @param arg
	 */
	public Date toDate(String arg) {
		try {
			return DateUtils.parseDate(arg, dataPatterns);
		} catch (ParseException e) {
			String message = "日期数据转换失败！";
			logger.error(message, e);
			throw new SystemException(message, SystemErrorCode.A_DATA_PARSE_ERROR);
		}
	}

}
